package com.itheima.reggie.controller;


import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.R;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.UUID;

@RestController
@RequestMapping("/common")
public class CommonController {

    @Value("${reggie.path}")
    private String imgPath;

    @PostMapping("/upload")
    public R upload(MultipartFile file){

        //接收上传来的文件，生成新的文件名（避免文件名重复）
        String originalFilename = file.getOriginalFilename();
        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));

        String newFileName = UUID.randomUUID().toString() + substring;
        //判定存储图片的目录是否存在，如果不存在，创建该目录
        File file1 = new File(imgPath);
        if (!file1.exists()){
            file1.mkdirs();
        }
        //将图片转存到该目录中
        try {
            file.transferTo(new File(imgPath+newFileName));
        } catch (IOException e) {
            e.printStackTrace();
            throw new CustomException("上传失败");
        }


        return R.success(newFileName);
    }

    @GetMapping("/download")
    public void download(HttpServletResponse response,String name){

      //组装文件路径
        try {
            String filename = imgPath+name;
            //读取文件，字节数组
            byte[] content = FileCopyUtils.copyToByteArray(new File(filename));
            //  将文件响应回去
            response.getOutputStream().write(content);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @GetMapping("/download2")
    public void download2(HttpServletResponse response,String name){

        //组装文件路径
        try {
            String filename = imgPath+name;
            //读取文件，字节数组
            byte[] content = FileCopyUtils.copyToByteArray(new File(filename));
            //  将文件响应回去
            response.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(name,"utf-8"));
            response.getOutputStream().write(content);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
